package com.jsaas.sys.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jsaas.model.RolePermission;
import com.jsaas.utils.MyUtils;

/**   
* @Title: RolePermissionService.java 
* @Package com.jsaas.sys.service 
* @Description: TODO(角色权限) 
* @author tuozq 
* @date 2017年12月20日 上午11:29:25 
* @version V1.0   
*/
public class RolePermissionService {
	
	public Ret save(String roleId, String permissionIds){
		if(StrKit.isBlank(roleId)){
			return Ret.fail().set("msg", "角色ID不能为空。");
		}
		if(StrKit.isBlank(permissionIds)){
			//删除角色的所有权限
			deleteByRoleId(roleId);
		}else{
			String[] permissions = permissionIds.split(",");
			SqlPara sqlPara = Db.getSqlPara("rolepermission.findByRoleId", Kv.by("roleId", roleId));
			List<RolePermission> rolePerms = RolePermission.dao.find(sqlPara);
			List<String> hasPermissions = new ArrayList<String>();//拥有的权限
			for (RolePermission rolePerm : rolePerms) {
				hasPermissions.add(rolePerm.getPermissionId());
			}
			List<RolePermission> addPermissions = new ArrayList<RolePermission>();//新增的权限
			for (int i = 0; i < permissions.length; i++) {
				String permissionId = permissions[i];
				if(!hasPermissions.contains(permissionId)){
					RolePermission rolePerm = new RolePermission();
					rolePerm.setId(MyUtils.newId());
					rolePerm.setPermissionId(permissionId);
					rolePerm.setRoleId(roleId);
					addPermissions.add(rolePerm);
				}
			}
			
			Db.update("delete from sys_role_permission where role_id = '"+ roleId +"' and permission_id not in ('"+ StringUtils.join(permissions, "','") +"')");
			Db.batchSave(addPermissions, 200);
		}
		return Ret.ok();
	}
	
	/**
	 * 删除角色的所有权限
	 */
	public void deleteByRoleId(String roleId){
		SqlPara sqlPara = Db.getSqlPara("rolepermission.deleteByRoleId", Kv.by("roleId", roleId));
		Db.update(sqlPara);
	}
	
}
